package com.neu.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.google.common.base.Strings;
import com.neu.constant.ResultCodeEnum;
import com.neu.pojo.User;
import com.neu.service.UserService;
import com.neu.service.impl.UserServiceImpl;
import com.neu.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Slf4j
@RestController
@RequestMapping(value = "/user", produces = {"application/json;charset=UTF-8"})
public class UserController {

    @Resource
    private UserService userService;

    @PostMapping("/login")
    public Object login(@RequestBody User user) {
        if (Objects.isNull(user) || Strings.isNullOrEmpty(user.getAccount()) || Strings.isNullOrEmpty(user.getPassword())) {
            return Result.error(ResultCodeEnum.PARAM_CHECK_ERROR);
        }
        log.info("用户登录： {}",user.getAccount());
        Object res = userService.login(user);
        return Objects.isNull(res)?Result.error(ResultCodeEnum.LOGIN_FAIL):res;
    }
    @GetMapping("/info")
    public Object info() {
        log.info("查询用户信息:{}",StpUtil.getLoginId());
        return userService.info();
    }
    @PostMapping("/logout")
    public Object logout() {
        userService.logout();
        return Result.success("ok");
    }

    @GetMapping("/list")
    public Object list(){
        log.info("查询用户列表...");
        return userService.list();
    }

    @PostMapping("/add")
    public Object add(@RequestBody User user){
        log.info("新增用户：{}",user);
        if (Objects.isNull(user) || Strings.isNullOrEmpty(user.getAccount()) || Strings.isNullOrEmpty(user.getPassword())) {
            return Result.error(ResultCodeEnum.PARAM_CHECK_ERROR);
        }
        if (Objects.nonNull(userService.queryUserInfoByAccount(user.getAccount()))){
            return Result.error(ResultCodeEnum.ACCOUNT_EXISTED);
        }
        return userService.add(user);
    }

    @PostMapping("/update")
    public Object update(@RequestBody User user) {
        log.info("修改用户信息:{}",user);
        return userService.update(user);
    }
    @PostMapping("/delete")
    public Object delete(Integer id) {
        log.info("删除用户:{}",id);
        return userService.delete(id);
    }



}
